package com.imprenta.ejb;


import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.primefaces.model.UploadedFile;

import com.hibernate.util.HibernateUtil;
import com.imprenta.entities.Imagentest;
import com.imprenta.entities.Test;

public class EjbFileUpload {
	
	public static void saveImage(UploadedFile _file){
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			byte[] bFile = _file.getContents();
			/*hacer el cambio cuando inserte en la bd ya q esta es solo una tabla de prueba*/
			Imagentest iTest = new Imagentest();
			iTest.setDescripcion(_file.getFileName());
			iTest.setImagen(bFile);
			
			session.save(iTest);
			session.getTransaction().commit();			
			/*
			Test test2 = (Test)session.get(Imagentest.class, iTest.getIdimagen());
			byte[] bImagen = test2.getImagen();
			
			FileOutputStream outputStream = new FileOutputStream("C:\\Compartida\\folder\\"+_file.getFileName());
			outputStream.write(bImagen);
			outputStream.close();*/
		} catch (HibernateException he) {
			// TODO: handle exception
			he.printStackTrace();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally{
			if (session != null) {
				session.close();
			}
		}
	}//fin saveimage
	
	public static void getImage(){
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			String q = "select t.id, t.nombre, t.imagen from Test t";
			Query query = session.createQuery(q);			
			Test test = new Test();
			
			for (int i = 0; i < query.list().size(); i++) {
				Object[] items = (Object[])query.list().get(i);
				test.setId(Integer.parseInt(items[0].toString()));
				//test.setImagen(items[2].)
			}
		} catch (HibernateException he) {
			// TODO: handle exception
			he.printStackTrace();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally{
			if (session != null) {
				session.close();
			}
		}
	}//fin getimage

}
